package top.icecola.community.service;

import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.HtmlUtils;
import top.icecola.community.dao.CommentMapper;
import top.icecola.community.domain.Comment;
import top.icecola.community.domain.CommentExample;
import top.icecola.community.util.CommunityConstant;
import top.icecola.community.util.SensitiveFilter;

import java.util.List;

@Service
public class CommentService implements CommunityConstant{

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private SensitiveFilter sensitiveFilter;

    @Autowired
    private DiscussPostService discussPostService;

//    查询评论
    public List<Comment> pageDiscussPosts(int entityType,int entityId,int pageNum, int pageSize){
        PageHelper.startPage(pageNum,pageSize);
        CommentExample commentExample = new CommentExample();
        commentExample.createCriteria().andStatusEqualTo(0).andEntityTypeEqualTo(entityType).andEntityIdEqualTo(entityId);
        commentExample.setOrderByClause("create_time asc");
        return commentMapper.selectByExample(commentExample);
    }

    public int selectCountComment(int entityType,int entityId){
        CommentExample commentExample = new CommentExample();
        commentExample.createCriteria().andStatusEqualTo(0).andEntityTypeEqualTo(entityType).andEntityIdEqualTo(entityId);
        List<Comment> comments = commentMapper.selectByExample(commentExample);
        return comments.size();
    }

//    增加评论
    @Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRED)
    public int addComment(Comment comment){
        if(comment==null){
            throw new IllegalArgumentException("参数不能为空");
        }
//        添加评论
        comment.setContent(HtmlUtils.htmlEscape(comment.getContent()));
        comment.setContent(sensitiveFilter.filter(comment.getContent()));
        int rows = commentMapper.insert(comment);
//        更新帖子评论数量
        if(comment.getEntityType()==ENTITY_TYPE_POST){
            int count = selectCountComment(comment.getEntityType(), comment.getEntityId());
            discussPostService.updateDiscussPostComment(comment.getEntityId(),count);
        }
        return rows;
    }

    public Comment findCommentById(Integer entityId) {
        CommentExample commentExample = new CommentExample();
        commentExample.createCriteria().andIdEqualTo(entityId);
        List<Comment> comments = commentMapper.selectByExample(commentExample);
        if(comments.isEmpty()){
            return null;
        }else{
            return comments.get(0);
        }
    }
}

